package com.zm.core.controller;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONObject;

import com.taobao.api.internal.util.WebUtils;
import com.zm.core.common.controller.BaseController;
import com.zm.taobao.APITest;

public class BusinessController extends BaseController {

	public void index() {

		String code = getPara("code");
		String token = getToken(code);
		APITest.testUserGet(token);
		// render("business/business.html");
	}

	public String getToken(String code) {
		String url = "https://oauth.tbsandbox.com/token";//沙箱获取token
		// String url = "https://oauth.taobao.com/token";
		Map<String, String> props = new HashMap<String, String>();
		props.put("grant_type", "authorization_code");
		/* 测试时，需把test参数换成自己应用对应的值 */
		props.put("code", code);
		props.put("client_id", "1023232930");
		props.put("client_secret", "sandbox484fea428feebf80c9fa689e8");
		props.put("redirect_uri", "http://27.210.132.99:9000/shoesize/business");
		props.put("view", "web");
		String json_text = "";
		String token = "";
		try {
			WebUtils.setIgnoreSSLCheck(true);
			json_text = WebUtils.doPost(url, props, 30000, 30000);
			System.out.println(json_text);
			// JSONObject JSONObject obj = (JSONObject) JSON.parse(json_text);
			JSONObject obj = JSONObject.fromObject(json_text);
			// access_token
			token = obj.get("access_token").toString();
			// Access token的类型目前只支持bearer
			obj.get("token_type").toString();
			// Access token过期时间
			obj.get("expires_in").toString();
			// Refresh token
			obj.get("refresh_token").toString();
			// Refresh token过期时间
			obj.get("re_expires_in").toString();
			// r1级别API或字段的访问过期时间
			obj.get("r1_expires_in").toString();
			// r2级别API或字段的访问过期时间
			obj.get("r2_expires_in").toString();
			// w1级别API或字段的访问过期时间
			obj.get("w1_expires_in").toString();
			// w2级别API或字段的访问过期时间
			obj.get("w2_expires_in").toString();
			// 淘宝账号
			URLDecoder.decode(obj.get("taobao_user_nick").toString(), "UTF-8");
			// 淘宝帐号对应id
			obj.get("taobao_user_id").toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return token;
	}
}
